<template>
  <view class="work-order-process-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <text class="page-title">工单处理</text>
        <text class="page-subtitle">{{ workOrderId }}</text>
      </view>
    </view>

    <!-- 处理描述输入 -->
    <view class="description-card">
      <view class="card-header">
        <text class="card-title">📝 处理描述</text>
        <text class="char-count" :class="charCountClass">{{ description.length }}/20</text>
      </view>
      <textarea
        v-model="description"
        placeholder="请详细描述处理过程和结果，至少需要20个字符..."
        class="description-input"
        maxlength="500"
        @input="onDescriptionChange"
      ></textarea>
      <view v-if="showDescriptionError" class="error-tip">
        还需要{{ 20 - description.length }}个字符
      </view>
    </view>

    <!-- 照片上传 -->
    <view class="photos-card">
      <view class="card-header">
        <text class="card-title">📸 处理照片</text>
        <text class="photo-count">{{ photos.length }}/10</text>
      </view>

      <view class="photos-grid">
        <!-- 已上传的照片 -->
        <view
          v-for="(photo, index) in photos"
          :key="index"
          class="photo-item"
        >
          <image :src="photo" class="photo-preview" mode="aspectFill"></image>
          <view class="photo-remove" @click="removePhoto(index)">
            <text class="remove-icon">❌</text>
          </view>
        </view>

        <!-- 上传按钮 -->
        <view v-if="photos.length < 10" class="upload-btn" @click="choosePhoto">
          <view class="upload-icon">📷</view>
          <view class="upload-text">上传照片</view>
        </view>
      </view>
      <view v-if="showPhotoWarning" class="warning-tip">
        ⚠️ 请至少上传2张照片作为处理证据
      </view>
    </view>

    <!-- 额外信息 (可选) -->
    <view class="additional-card">
      <view class="card-header">
        <text class="card-title">🔧 额外信息 (可选)</text>
      </view>

      <view class="additional-item">
        <text class="additional-label">使用材料</text>
        <input
          v-model="materialsUsed"
          placeholder="使用的材料，多个用逗号分隔"
          class="additional-input"
        </input>
      </view>

      <view class="additional-item">
        <text class="additional-label">发现问题</text>
        <input
          v-model="issuesFound"
          placeholder="发现的问题，多个用逗号分隔"
          class="additional-input"
        </input>
      </view>

      <view class="additional-item">
        <text class="additional-label">维护建议</text>
        <input
          v-model="recommendations"
          placeholder="维护建议，多个用逗号分隔"
          class="additional-input"
        </input>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button
        class="btn btn-submit"
        :disabled="!canSubmit || processing"
        @click="submitProcessing"
      >
        <text v-if="processing">处理中...</text>
        <text v-else-if="!canSubmit">请完成要求</text>
        <text v-else>完成处理</text>
      </button>

      <button class="btn btn-cancel" @click="cancelProcessing">
        取消处理
      </button>
    </view>

  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useWorkOrderProcessStore } from '@/stores/work-order-process'

// 页面参数
const workOrderId = ref('')

// 处理存储
const workOrderProcessStore = useWorkOrderProcessStore()

// 表单数据
const description = ref('')
const photos = ref<string[]>([])
const materialsUsed = ref('')
const issuesFound = ref('')
const recommendations = ref('')
const processing = ref(false)

// 页面加载
onLoad((options) => {
  if (options?.id) {
    workOrderId.value = options.id
    // 初始化处理数据
    workOrderProcessStore.startProcessing(workOrderId.value)
  }
})

// 计算属性
const canSubmit = computed(() => {
  return description.value.length >= 20 && photos.value.length >= 2
})

const showDescriptionError = computed(() => {
  return description.value.length > 0 && description.value.length < 20
})

const showPhotoWarning = computed(() => {
  return photos.value.length > 0 && photos.value.length < 2
})

const charCountClass = computed(() => {
  return description.value.length < 20 ? 'error' : ''
})

// 提交处理
const submitProcessing = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完成处理要求',
      icon: 'none'
    })
    return
  }

  processing.value = true

  try {
    // 构建额外数据
    const additionalData: any = {}
    if (materialsUsed.value) {
      additionalData.materialsUsed = materialsUsed.value.split(',').map(item => item.trim())
    }
    if (issuesFound.value) {
      additionalData.issuesFound = issuesFound.value.split(',').map(item => item.trim())
    }
    if (recommendations.value) {
      additionalData.recommendations = recommendations.value.split(',').map(item => item.trim())
    }

    // 调用存储完成处理
    await workOrderProcessStore.completeProcessing(
      workOrderId.value,
      description.value,
      photos.value,
      additionalData
    )

    uni.showToast({
      title: '处理完成',
      icon: 'success'
    })

    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)

  } catch (error: any) {
    uni.showToast({
      title: error.message || '处理失败',
      icon: 'none'
    })
  } finally {
    processing.value = false
  }
}

// 选择照片
const choosePhoto = () => {
  uni.chooseImage({
    count: Math.min(10 - photos.value.length, 9),
    sizeType: ['compressed'],
    sourceType: ['camera', 'album'],
    success: (res) => {
      res.tempFilePaths.forEach((path) => {
        if (photos.value.length < 10) {
          photos.value.push(path)
        }
      })
    },
    fail: (err) => {
      uni.showToast({
        title: '选择照片失败',
        icon: 'none'
      })
    }
  })
}

// 删除照片
const removePhoto = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这张照片吗？',
    success: (res) => {
      if (res.confirm) {
        photos.value.splice(index, 1)
      }
    }
  })
}

// 取消处理
const cancelProcessing = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消处理吗？已填写的内容将不会保存。',
    success: (res) => {
      if (res.confirm) {
        // 清理当前处理数据
        workOrderProcessStore.clearCurrentProcess()
        uni.navigateBack()
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.work-order-process-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  padding: 24rpx;
  padding-bottom: 40rpx;
}

// 页面头部
.page-header {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  padding: 32rpx;
  margin: -24rpx -24rpx 24rpx;
  color: #ffffff;

  .header-content {
    text-align: center;
  }

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 8rpx;
  }

  .page-subtitle {
    font-size: 24rpx;
    opacity: 0.9;
  }
}

// 描述卡片
.description-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .char-count {
      font-size: 24rpx;
      color: #999;

      &.error {
        color: #ff4d4f;
        font-weight: bold;
      }
    }
  }

  .description-input {
    width: 100%;
    min-height: 200rpx;
    padding: 24rpx;
    border: 2rpx solid #e8e8e8;
    border-radius: 16rpx;
    font-size: 28rpx;
    line-height: 1.6;

    &:focus {
      border-color: #52c41a;
      box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
    }
  }
}

// 错误提示
.error-tip {
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #ff4d4f;
  font-weight: 500;
}

// 警告提示
.warning-tip {
  margin-top: 16rpx;
  padding: 16rpx;
  background: #fff7e6;
  border-radius: 12rpx;
  font-size: 24rpx;
  color: #faad14;
  font-weight: 500;
}

// 照片卡片
.photos-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .photo-count {
      font-size: 24rpx;
      color: #999;
    }
  }

  .photos-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16rpx;

    .photo-item {
      position: relative;
      aspect-ratio: 1;
      border-radius: 16rpx;
      overflow: hidden;
      background: #f8f8f8;

      .photo-preview {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .photo-remove {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        width: 40rpx;
        height: 40rpx;
        background: rgba(255, 77, 79, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;

        .remove-icon {
          font-size: 24rpx;
          color: #ffffff;
        }
      }
    }

    .upload-btn {
      aspect-ratio: 1;
      border: 2rpx dashed #e8e8e8;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #fafafa;

      .upload-icon {
        font-size: 48rpx;
        color: #999;
        margin-bottom: 8rpx;
      }

      .upload-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

// 额外信息卡片
.additional-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .card-header {
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .additional-item {
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .additional-label {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 12rpx;
      font-weight: 500;
    }

    .additional-input {
      width: 100%;
      height: 80rpx;
      padding: 0 24rpx;
      border: 2rpx solid #e8e8e8;
      border-radius: 16rpx;
      font-size: 28rpx;
      background: #fafafa;

      &:focus {
        border-color: #52c41a;
        background: #ffffff;
        box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
      }
    }
  }
}

// 提交区域
.submit-section {
  margin-top: 48rpx;
  display: flex;
  gap: 24rpx;

  .btn {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    &:disabled {
      opacity: 0.6;
    }

    &.btn-submit {
      background: linear-gradient(135deg, #52c41a, #73d13d);
      color: #ffffff;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

      &:disabled {
        background: #ccc;
        box-shadow: none;
      }
    }

    &.btn-cancel {
      background: #ffffff;
      color: #666;
      border: 2rpx solid #e8e8e8;
    }
  }
}
</style>